package top.loveeveryone.configPage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.plugin.dom.core.CoreConstants;
import top.loveeveryone.configPage.document.Serverconfig;
import top.loveeveryone.configPage.param.ConfigFileReq;
import top.loveeveryone.configPage.param.Result;

import javax.annotation.Resource;
import java.util.zip.CRC32;

@Component
public class ConfigFilePage {
    private static final Logger log = LoggerFactory.getLogger(ConfigFilePage.class);


    @Value("${uri.7daytodie}")
    private String uri;

    @Value("${uri.7daytodieInterpret}")
    private String InterpretUri;

    @Resource
    private Serverconfig serverconfig;

    public Result getConfig() {
        JSONArray bar = new JSONArray();
        try {
            Document document = serverconfig.parse(uri);
            bar = serverconfig.bar(document);
            if (!InterpretUri.isEmpty()) {
                for (int i = 0, index = bar.size(); i < index; i++) {
                    JSONObject jsonObject = bar.getJSONObject(i);
                    String name = jsonObject.getString("name");
                    Document interpret = serverconfig.parse(InterpretUri);
                    String interpretString = serverconfig.selectTranslate(interpret, "//*[@name='" + name + "']");
                    jsonObject.put("interpret",interpretString);
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
            return Result.fail("请求失败");
        }
        return Result.success(bar);
    }

    public Result upDataConfig(ConfigFileReq configFileReq) {
        System.out.println(configFileReq);
        try {
            Document document = serverconfig.parse(uri);
            Document upDataXml = DocumentHelper.createDocument();
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(configFileReq);
            JSONArray jsonArray = jsonObject.getJSONArray("serverConfig");
            for (int i = 0, index = jsonArray.size(); i < index; i++) {
                jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.getString("name");
                String value = jsonObject.getString("value");
                upDataXml = serverconfig.upDataXml(document, "//*[@name='" + name + "']", value);
            }
            serverconfig.outFile(upDataXml,uri);
        }catch (Exception e){
            return Result.fail("修改失败");
        }
        return Result.success();
    }
}
